package com.binzaijun.stock.service;

import com.binzaijun.stock.common.ExchangeEnum;
import com.binzaijun.stock.constant.Constants;
import com.binzaijun.stock.domain.QtStock;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class StockStringService {

    private static final Logger logger = LoggerFactory.getLogger(StockStringService.class);

    /**
     * 解析腾讯股票数据字符串
     */
    public QtStock parseQtStockString(String str) {
        if (StringUtils.isBlank(str)) {
            logger.warn("股票数据字符串为空");
            return null;
        }

        try {
            String[] stock = str.split(Constants.QUOTES);
            if (stock.length < 2) {
                return null;
            }

            str = stock[1];
            stock = str.split(Constants.TILDE);

            if (stock.length < 10) {
                return null;
            }

            int exchange = Integer.parseInt(stock[0]);
            String stockName = stock[1];
            String stockSymbol = ExchangeEnum.fromValue(exchange) + stock[2];
            double currentPrice = Double.parseDouble(stock[3]);
            double change = Double.parseDouble(stock[4]);
            double changePercentage = Double.parseDouble(stock[5]);
            long volume = Long.parseLong(stock[6]);
            double turnover = Double.parseDouble(stock[7]);
            double marketValue = Double.parseDouble(stock[9]);

            return new QtStock(stockSymbol, stockName, exchange, currentPrice,
                    change, changePercentage, volume, turnover, marketValue);

        } catch (Exception e) {
            logger.error("解析股票数据失败: {}", str, e);
            return null;
        }
    }

    /**
     * 格式化URL参数
     */
    public String formatUrlParameters(List<String> stockSymbols) {
        if (stockSymbols == null || stockSymbols.isEmpty()) {
            return "";
        }

        List<String> prefixedList = stockSymbols.stream()
                .map(str -> "s_" + str)
                .collect(Collectors.toList());

        return String.join(Constants.COMMA, prefixedList);
    }
}